﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;

using VIT.Web.UI;
using VIT.Web.Controls;
using VIT.Provider;
using VIT.Library;

namespace VIT.Web.Admin
{
    public partial class AccountEdit : VITComponent
    {
        Provider.Account acc;
        protected void Page_Load(object sender, EventArgs e)
        {            
            acc = new Provider.Account();
            acc.UserName = Request["usr"]; 
            if(!IsPostBack) LoadData();            
        }

        #region Methods
        private void LoadData()
        {
            acc.GetSingle();

            if (!string.IsNullOrEmpty(acc.UserName))
            {
                // kiểm tra user cần sửa coa phải thuộc tập con của user hiện tại
                string[] arrChild = acc.GetAll(ChildId: "Administrator").GetAllChildId(Session["userName"].ToString(), "CreateByUser", "UserName").Split(',');
                List<string> lstChild = arrChild.ToList();
                if (lstChild.Contains(acc.UserName))
                {
                    UserName.Text = acc.UserName;
                    UserName.ReadOnly = true;
                    Password.Visible = false;
                    FullName.Text = acc.FullName;
                }
                else
                {
                    RedirectComponent("Account", "AccountList");
                }

                ButtonModify.Visible = true;
            }
            else ButtonInsert.Visible = true; 
        }

        private void SaveData()
        {
            acc.UserName = UserName.Text;
            acc.Password = Password.Text.EnCodeMD5();
            acc.FullName = FullName.Text;            

            if (acc.Save()) setTrueVisible(lblThanhCong);
            else setTrueVisible(lblThatBai);            
        }

        private void setTrueVisible(System.Web.UI.HtmlControls.HtmlGenericControl control)
        {
            lblThanhCong.Visible = false;
            lblThatBai.Visible = false;

            control.Visible = true;
        }
        #endregion

        #region Events
        protected void Save_Click(object sender, EventArgs e)
        {
            SaveData();

            RedirectComponent("Account", "AccountList");
        }

        protected void Apply_Click(object sender, EventArgs e)
        {
            SaveData();
            LoadData();
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            RedirectComponent("Account", "AccountList");
        }
        #endregion
    }
}